package com.wo.cloud.tenant.handler;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.wo.cloud.core.context.TenantContextHolder;
import com.wo.cloud.tenant.props.TenantConfigProperties;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/4/11 16:49
 * Description: https://baomidou.com/guide/interceptor-tenant-line.html#tenantlineinnerinterceptor
 */

@Slf4j
public class WoCloudTenantHandler implements TenantLineHandler {

    @Autowired
    private TenantConfigProperties tenantConfigProperties;

    // TODO: new LongValue(1)

    /**
     * 获取租户 ID 值表达式，只支持单个 ID 值
     * <p>
     *
     * @return 租户 ID 值表达式
     */
    @Override
    public Expression getTenantId() {
        // 获取tenant id
        String tenantId = TenantContextHolder.getTenantId();
        System.out.println("tenant2 : " + tenantId);
        if (StrUtil.isNotBlank(tenantId)) {
            return new StringValue(tenantId);
        }
        return new NullValue();
    }


    /**
     * 获取租户字段名
     * <p>
     * 默认字段名叫: tenant_id
     *
     * @return 租户字段名
     */
    @Override
    public String getTenantIdColumn() {
        return tenantConfigProperties.getColumn();
    }


    /**
     * 根据表名判断是否忽略拼接多租户条件
     * <p>
     * 默认都要进行解析并拼接多租户条件
     *
     * @param tableName 表名
     * @return 是否忽略, true:表示忽略，false:需要解析并拼接多租户条件
     */
    @Override
    public boolean ignoreTable(String tableName) {
        System.out.println("properties: " + tenantConfigProperties);

        System.out.println("id " + getTenantId());

        // TODO:
        // 如果租户id为空，则忽略租户过滤
        System.out.println("tableName:" + tableName);

        System.out.println(tenantConfigProperties.getIgnoreTables());

        return tenantConfigProperties.getIgnoreTables().stream().anyMatch((t) -> t.equalsIgnoreCase(tableName));
    }
}
